import axios from 'axios'
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { tansParams, blobValidate } from "@/utils/collegeHrSystemUI";
import { saveAs } from 'file-saver'
import request from '@/utils/request'
/**
 * 通用上传路径
 */
const uploadUrl = process.env.VUE_APP_BASE_API + '/file/commonUpload'
/**
 * 返回全部附件信息上传路径
 */
const uploadAndGetFileAllUrl = process.env.VUE_APP_BASE_API + '/file/uploadAndGetFileAll'
/**
 * 回显附件前缀
 */
const echoPrefix = process.env.VUE_APP_BASE_API + '/upload/'
/**
 * 下载附件路径
 */
const downloadUrl = '/file/commonDownload'
/**
 * 上传token相关请求头
 */
const uploadHeaders = {
  Authorization: "Bearer " + getToken(),
}

/**
 * @param {Object} url 下载地址
 * @param {Object} params 参数
 * @param {Object} filename 原文件名
 */
export function download(params) {
  // 创建axios实例
  const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: process.env.VUE_APP_BASE_API,
    // 超时
    timeout: 10000
  })
  return service.post(downloadUrl, params, {
    // transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/json','Authorization':'Bearer ' + getToken()},
    responseType: 'blob'
  }).then(async (res) => {
    const filename = res.headers["content-disposition"];
    const blob = new Blob([res.data]);
    var downloadElement = document.createElement("a");
    var href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    downloadElement.download = decodeURIComponent(filename.split("filename=")[1]);
    document.body.appendChild(downloadElement);
    downloadElement.click();
    document.body.removeChild(downloadElement);
    window.URL.revokeObjectURL(href);
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误，请联系管理员！')
  })
}

/**
 * @param {Object} data
 */
export function deleteFile(data) {
  return request({
    url: '/file/deleteFile',
    method: 'delete',
    data: data
  })
}
/**
 * @param {Object} 列表查询参数
 */
export function getFileList(data) {
  return request({
    url: '/file/getFileList',
    method: 'get',
    params: data
  })
}

export{
  uploadUrl,
  uploadAndGetFileAllUrl,
  uploadHeaders,
  echoPrefix,
}
